package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Logininfo;
import cn.itsource.ymcc.dto.LoginDto;
import cn.itsource.ymcc.jwt.JwtUtils;
import cn.itsource.ymcc.jwt.PayloadData;
import cn.itsource.ymcc.jwt.RsaUtils;
import cn.itsource.ymcc.mapper.LogininfoMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ILogininfoService;
import cn.itsource.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author whale.chen
 * @since 2023-02-24
 */
@Service
public class LogininfoServiceImpl extends ServiceImpl<LogininfoMapper, Logininfo> implements ILogininfoService {
    @Value("${jwt.rsa.pri}")
    private String pri;
    /**
     * 统一认证接口：前后台通用
     * @param loginDto
     * @return
     */
    @Override
    public JsonResult accountLogin(LoginDto loginDto) {
        //1.根据用户名查询数据 select * from t_logininfo where username = ?
        Logininfo logininfo = baseMapper.selectOne(new QueryWrapper<Logininfo>()
                .eq("username", loginDto.getUsername()));

        //2.校验查询的对象非空
        AssertUtil.isTrue(logininfo != null, "用户名不存在！");

        //3.校验密码：加密规则是BCryptPasswordEncoder
        AssertUtil.isTrue(new BCryptPasswordEncoder().matches(loginDto.getPassword(), logininfo.getPassword()), "密码错误！");

        /**
         * 4.登录成功
         *  1）利用jwt工具类 私钥加密，将logininfo对象作为载荷，生成JWT字符串
         *  2）JWT字符串和logininfo对象数据封装到HashMap返回前端
         */
        try {
            //放入载荷的东西
            PayloadData payloadData = new PayloadData();
            logininfo.setPassword(null);
            payloadData.setLogininfo(logininfo);
            //判断是不是管理员
            if(loginDto.getType() == 0){
                //连表查询用户拥有的权限sn
//                List<String> permissionsByRoleIds = roleMapper.getPermissionsByRoleIds(roles);
                //设置权限
//                payloadData.setPermissions(new HashSet<>(permissionsByRoleIds));
                //菜单:  连表查询 先不做
//                List<Menu> all = iMenuService.findAll();
//                payloadData.setMenus(p);
            }
            //生成token
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(pri).getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 1200);

            Map<String,Object> map = new HashMap<>();
            map.put("jwtToken", token);
            map.put("logininfo", logininfo);
            return JsonResult.me(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("登录失败！");
        }
    }
}
